//给定一个包含 n 个整数的数组 nums 和一个目标值 target，判断 nums 中是否存在四个元素 a，b，c 和 d ，使得 a + b + c +
// d 的值与 target 相等？找出所有满足条件且不重复的四元组。 
//
// 注意：答案中不可以包含重复的四元组。 
//
// 
//
// 示例 1： 
//
// 
//输入：nums = [1,0,-1,0,-2,2], target = 0
//输出：[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
// 
//
// 示例 2： 
//
// 
//输入：nums = [], target = 0
//输出：[]
// 
//
// 
//
// 提示： 
//
// 
// 0 <= nums.length <= 200 
// -109 <= nums[i] <= 109 
// -109 <= target <= 109 
// 
// Related Topics 数组 双指针 排序 
// 👍 911 👎 0


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {

        List<List<Integer>> result = new ArrayList<>();
        List<Integer> resultItem;
        Arrays.sort(nums);

        int first,second,third,idxThird,last,idxLast,sum,length = nums.length;

        for (int i = 0; i < length - 3; i++ ) {
            first = nums[i];
            if (i > 0 && first == nums[i-1]){
                continue;
            }
            for (int j = i + 1; j < length - 2; j++) {
                second = nums[j];
                if ((j > i+1) && second == nums[j-1]){
                    continue;
                }
                idxThird = j + 1;
                third = nums[idxThird];
                idxLast = length - 1;
                last = nums[idxLast];

                while (idxThird < idxLast){
                    if ((idxThird > j+1) && third == nums[idxThird-1]){
                        third = nums[++idxThird];
                        continue;
                    }
                    if ((idxLast < length - 1) && last == nums[idxLast+1]){
                        last = nums[--idxLast];
                        continue;
                    }

                    sum = first + second + third + last;

                    if (sum < target){
                        third = nums[++idxThird];
                    }else if (sum > target){
                        last = nums[--idxLast];
                    }else {
                        resultItem = new ArrayList<>();
                        resultItem.add(first);
                        resultItem.add(second);
                        resultItem.add(third);
                        resultItem.add(last);
                        result.add(resultItem);
                        third = nums[++idxThird];
                        last = nums[--idxLast];
                    }
                }
            }
        }

        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)
